package httpx

import (
	"encoding/json"
	"io"
	"net/http"

	"casbinx/model"

	"github.com/casbin/casbin/v2"
)

func Authorize(e *casbin.Enforcer) http.HandlerFunc {
	return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		action := "read"
		switch request.Method {
		case "GET":
			action = "read"
		case "POST", "PUT", "DELETE":
			action = "write"
		default:
		}

		all, err := io.ReadAll(request.Body)
		if err != nil {
			return
		}
		var user model.User
		err = json.Unmarshal(all, &user)
		if err != nil {
			return
		}
		path := request.URL.Path
		if ok, _ := e.Enforce(user.Username, path, action); ok {
		} else {
			writer.WriteHeader(http.StatusUnauthorized)
			writer.Write([]byte("error:沒有權限"))
		}
	})
}
